package org.jeecg.modules.chg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.service.IBasePeriodService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.jeecg.modules.chg.entity.ChgFees;
import org.jeecg.modules.chg.entity.ChgSubFees;
import org.jeecg.modules.chg.service.IChgBillService;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.chg.service.IChgSubFeesService;
import org.jeecg.modules.chg.vo.ChgChargeFeeVo;
import org.jeecg.modules.chg.vo.ChgFeePrintVo;
import org.jeecg.modules.chg.vo.ChgFeesPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 收费记录
 * @Author: jeecg-boot
 * @Date:   2022-02-21
 * @Version: V1.0
 */
@Api(tags="收费记录")
@RestController
@RequestMapping("/chg/chgFees")
@Slf4j
public class ChgFeesController {
	@Autowired
	private IChgFeesService chgFeesService;
	@Autowired
	private IChgSubFeesService chgSubFeesService;
 	@Autowired
 	private IArcAccountService arcAccountService;
 	@Autowired
 	private IBasePeriodService basePeriodService;
 	@Autowired
	private IChgBillService chgBillService;

	/**
	 * 分页列表查询
	 *
	 * @param chgFees
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "收费记录-分页列表查询")
	@ApiOperation(value="收费记录-分页列表查询", notes="收费记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ChgFees chgFees,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ChgFees> queryWrapper = QueryGenerator.initQueryWrapper(chgFees, null);
		queryWrapper.eq("del_flag",0);
		queryWrapper.eq("status",1);
		queryWrapper.orderByAsc("cus_id");
		queryWrapper.orderByDesc("read_month");
		Page<ChgFees> page = new Page<ChgFees>(pageNo, pageSize);
		IPage<ChgFees> pageList = chgFeesService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * mp分页列表查询
	  *
	  * {
	  * 	"data": [{
	  * 		"ctotal": "125箱",
	  * 		"cname": "牛奶0",
	  * 		"cprice": "56",
	  * 		"riqi": "2021年08月11日",
	  * 		"id": 100,
	  * 		"dtotal": "1256箱",
	  * 		"tp": "7000",
	  * 		"ztotal": "589箱",
	  * 		"cnum": "每箱12瓶",
	  * 		"dId": "1"
	  *        }],
	  *         "total": 1, //total（总页数），count（总条数）
	  *
	  * 	"count": 3
	  *
	  * }
	  * @param chgFees
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "收费记录-分页列表查询")
	 @ApiOperation(value="收费记录-分页列表查询", notes="收费记录-分页列表查询")
	 @GetMapping(value = "/mpList")
	 public JSONObject queryMpList(ChgFees chgFees,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 // 获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 System.out.println(sysUser.getRelTenantIds());
		 TenantContext.setTenant(sysUser.getRelTenantIds());

		 QueryWrapper<ChgFees> queryWrapper = QueryGenerator.initQueryWrapper(chgFees, req.getParameterMap());
		 Page<ChgFees> page = new Page<ChgFees>(pageNo, pageSize);
		 IPage<ChgFees> pageList = chgFeesService.page(page, queryWrapper);

		 JSONObject jsonObject = new JSONObject();

		 System.out.println(TenantContext.getTenant());

		 List<ChgFees> records = pageList.getRecords();
		 JSONArray rsArr= (JSONArray) JSONArray.toJSON(records);
		 jsonObject.put("data",rsArr);
		 jsonObject.put("total",pageList.getPages());
		 jsonObject.put("count",pageList.getTotal());
		 System.out.println(jsonObject.toJSONString());

		 return jsonObject;
	 }
	/**
	 * 分页列表查询-取消收费
	 *
	 * @param chgFees
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "收费记录-分页列表查询")
	@ApiOperation(value="收费记录-分页列表查询", notes="收费记录-分页列表查询")
	@GetMapping(value = "/cancelList")
	public Result<?> cancelList(ChgFees chgFees,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		List<String> cusIds=new ArrayList<>();
		String financialDate="";
		String financialMonth="";
		if(oConvertUtils.isNotEmpty(chgFees.getAccCode())){
			List<ArcAccountCusVO> cusVOList = arcAccountService.queryAccount(null,null,chgFees.getAccCode());
			if(null != cusVOList && cusVOList.size()>0) {
				cusIds = cusVOList.stream().map(ArcAccountCusVO::getCode).collect(Collectors.toList());
				chgFees.setAccCode(null);
			}
		}else{
			return Result.error("缴费账号不能为空");
		}
		if(oConvertUtils.isNotEmpty(chgFees.getFinancialDate())){
			financialDate=chgFees.getFinancialDate();
			chgFees.setFinancialDate(null);
		}
		if(oConvertUtils.isNotEmpty(chgFees.getFinancialMonth())){
			financialMonth=chgFees.getFinancialMonth();
			chgFees.setFinancialMonth(null);
		}

		QueryWrapper<ChgFees> queryWrapper = new QueryWrapper<ChgFees>();
		//BasePeriod basePeriod = basePeriodService.getOne(new LambdaQueryWrapper<BasePeriod>().eq(BasePeriod::getIsUsed, 1));
		if(null != cusIds && cusIds.size()>0){
			queryWrapper.in("cus_id",cusIds);
		}
		//queryWrapper.eq("financial_month",basePeriod.getMonth());
		queryWrapper.eq("status",1);
		queryWrapper.gt("money",0);
		if(oConvertUtils.isNotEmpty(financialDate)){
			queryWrapper.gt("financial_date",financialDate);
			String addDate = null;
			try {
				addDate = DateUtils.formatAddDate(financialDate, "yyyy-MM-dd", 1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			queryWrapper.lt("financial_date",addDate);
		}
		if(oConvertUtils.isNotEmpty(financialMonth)){
			queryWrapper.eq("financial_month",financialMonth);
		}
		List<ChgFees> feeslist=new ArrayList<>();
		if(oConvertUtils.isNotEmpty(financialMonth) || oConvertUtils.isNotEmpty(financialDate)){
			feeslist = chgFeesService.list(queryWrapper);
		}else{
			queryWrapper.eq("id","00000000");
			feeslist = chgFeesService.list(queryWrapper);
		}
		return Result.OK(feeslist);
	}
	/**
	 * 分页列表查询-取消收费
	 *
	 * @param chgFees
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "收费记录-分页列表查询")
	@ApiOperation(value="收费记录-分页列表查询", notes="收费记录-分页列表查询")
	@GetMapping(value = "/feeList")
	public Result<?> feeList(ChgFees chgFees,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//缴费账户对应 用户水表信息
		List<ArcAccountCusVO> cusVOList = arcAccountService.queryAccount(null,null,chgFees.getAccCode());

		if(null != cusVOList && cusVOList.size()>0) {

			Map<String, String> userMap = new HashMap<>();
			for (ArcAccountCusVO cusVO1 : cusVOList) {
				if (!userMap.containsKey(cusVO1.getCusId())) {
					userMap.put(cusVO1.getCusId(), cusVO1.getCode());
				}
			}
			List<String> cusIds = cusVOList.stream().map(ArcAccountCusVO::getCode).collect(Collectors.toList());

			QueryWrapper<ChgFees> queryWrapper = QueryGenerator.initQueryWrapper(chgFees, req.getParameterMap());
			queryWrapper.eq("status", 1);
			queryWrapper.in("cus_id",cusIds);
			queryWrapper.gt("money", 0);
			Page<ChgFees> page = new Page<ChgFees>(pageNo, pageSize);
			IPage<ChgFees> pageList = chgFeesService.page(page, queryWrapper);
			//动态找出规则表SKU
			pageList.getRecords().forEach(item->{
				item.setCusCode(userMap.get(item.getCusId()));
			});
			return Result.OK(pageList.getRecords());
		}
		return Result.OK(null);
	}

	/**
	 *   添加
	 *
	 * @param chgFeesPage
	 * @return
	 */
	@AutoLog(value = "收费记录-添加")
	@ApiOperation(value="收费记录-添加", notes="收费记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ChgFeesPage chgFeesPage) {
		ChgFees chgFees = new ChgFees();
		BeanUtils.copyProperties(chgFeesPage, chgFees);
		chgFeesService.saveMain(chgFees, chgFeesPage.getChgSubFeesList());
		return Result.OK("添加成功！");
	}
	/**
	 *   indexData
	 *
	 * @param chargeFeeVo
	 * @return
	 */
	@AutoLog(value = "首页数据")
	@ApiOperation(value="首页数据", notes="首页数据")
	@PostMapping(value = "/indexData")
	public Result<?> indexData(@RequestBody ChgChargeFeeVo chargeFeeVo) {
		return chgFeesService.indexData(chargeFeeVo,null);
	}
	/**
	 *   收费
	 *
	 * @param chargeFeeVo
	 * @return
	 */
	@AutoLog(value = "收费")
	@ApiOperation(value="收费", notes="收费")
	@PostMapping(value = "/chargeFee")
	public Result<?> chargeFee(@RequestBody ChgChargeFeeVo chargeFeeVo) {
		return chgFeesService.charge(chargeFeeVo);
	}
	/**
	 *   手动启动自动收费
	 *
	 * @param chargeFeeVo
	 * @return
	 */
	@AutoLog(value = "手动启动自动收费-一键扣费")
	@ApiOperation(value="手动启动自动收费", notes="手动启动自动收费")
	@PostMapping(value = "/keyUniteCharge")
	public Result<?> keyUniteCharge(@RequestBody ChgChargeFeeVo chargeFeeVo) {
		return chgFeesService.keyUniteCharge(chargeFeeVo);
	}
	/**
	 *   取消收费
	 *
	 * @param chargeFeeVo
	 * @return
	 */
	@AutoLog(value = "取消收费")
	@ApiOperation(value="收费", notes="收费")
	@PostMapping(value = "/cancelFee")
	public Result<?> cancelFee(@RequestBody ChgChargeFeeVo chargeFeeVo) {
		return chgFeesService.cancelCharge(chargeFeeVo);
	}
	/**
	 *   退费
	 *
	 * @param chargeFeeVo
	 * @return
	 */
	@AutoLog(value = "退费")
	@ApiOperation(value="退费", notes="退费")
	@PostMapping(value = "/returnFee")
	public Result<?> returnFee(@RequestBody ChgChargeFeeVo chargeFeeVo) {
		return chgFeesService.returnFee(chargeFeeVo);
	}

	 /**
	  *   收费票据打印数据
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "收费票据打印数据")
	 @ApiOperation(value="收费票据打印数据", notes="收费票据打印数据")
	 @RequestMapping(value = "/printBillData", method ={RequestMethod.GET, RequestMethod.POST})
	 public Result<?> printBillData(@RequestBody JSONObject billData) {

		 //return chgBillService.createFeePrintBillSj(billData);
		 return chgBillService.printBillData(billData);
	 }

	 /**
	  *   收费票据打印后提交
	  *
	  *	提交后有更改票据状态由占用为开票 而 收费记录和缴费记录没有对票据做任何修改
	  *
	  *	票据使用mws_t_bv_vouchers 记录缴费ID
	  * 票据使用明细mws_t_bv_vouchers 记录收费ID(chargeId)
	  *
	  * 可优化：在获取缴费记录的收费记录时（getFeeListByPayments），过滤掉该缴费记录已开票的收费记录
	  *
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "收费票据打印后提交")
	 @ApiOperation(value="收费票据打印后提交", notes="收费票据打印后提交")
	 @PostMapping(value = "/printBillSubmit")
	 public Result<?> printBillSubmit(@RequestBody JSONObject billData) {

		 Result<?> result = chgBillService.printBillData(billData);
		 if(result.isSuccess()){
			 List<ChgFeePrintVo> feePrintvoLs = (List<ChgFeePrintVo>) result.getResult();
			 return chgFeesService.printBillSubmit(billData,feePrintvoLs);
		 }

		 return Result.OK("打印完成");
	 }
	 /**
	  *   作废已打印的票据
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "作废已打印的票据")
	 @ApiOperation(value="作废已打印的票据", notes="作废已打印的票据")
	 @PostMapping(value = "/printVoidBill")
	 public Result<?> printVoidBill(@RequestBody JSONObject billData) {

	 	return chgFeesService.printVoidBill(billData);
	 }
	 /**
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "重打已打印的票据")
	 @ApiOperation(value="重打已打印的票据", notes="重打已打印的票据")
	 @PostMapping(value = "/printRepeatBill")
	 public Result<?> printRepeatBill(@RequestBody JSONObject billData) {

	 	//return chgBillService.printRepeatBillDataPdf(billData);
	 	return chgBillService.printRepeatBillData(billData);
	 }
	 /**
	  *   费用减免
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "费用减免")
	 @ApiOperation(value="费用减免", notes="费用减免")
	 @PostMapping(value = "/deratefee")
	 public Result<?> deratefeeBill(@RequestBody JSONObject billData) {

	 	return chgFeesService.deratefeeBill(billData);
	 }
	 /**
	  *   费用减免-违约金
	  *
	  * @param billData
	  * @return
	  */
	 @AutoLog(value = "费用减免")
	 @ApiOperation(value="费用减免", notes="费用减免")
	 @PostMapping(value = "/deratePenalty")
	 public Result<?> deratePenalty(@RequestBody JSONObject billData) {

	 	return chgFeesService.deratePenalty(billData);
	 }

	 /**
	 *  编辑
	 *
	 * @param chgFeesPage
	 * @return
	 */
	@AutoLog(value = "收费记录-编辑")
	@ApiOperation(value="收费记录-编辑", notes="收费记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ChgFeesPage chgFeesPage) {
		ChgFees chgFees = new ChgFees();
		BeanUtils.copyProperties(chgFeesPage, chgFees);
		ChgFees chgFeesEntity = chgFeesService.getById(chgFees.getId());
		if(chgFeesEntity==null) {
			return Result.error("未找到对应数据");
		}
		chgFeesService.updateMain(chgFees, chgFeesPage.getChgSubFeesList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收费记录-通过id删除")
	@ApiOperation(value="收费记录-通过id删除", notes="收费记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		chgFeesService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "收费记录-批量删除")
	@ApiOperation(value="收费记录-批量删除", notes="收费记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.chgFeesService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收费记录-通过id查询")
	@ApiOperation(value="收费记录-通过id查询", notes="收费记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ChgFees chgFees = chgFeesService.getById(id);
		if(chgFees==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(chgFees);

	}

	 /**
	  * 获取积木打印配置
	  *
	  * @param dbCode
	  * @return
	  */
	 @AutoLog(value = "获取积木打印配置")
	 @ApiOperation(value="获取积木打印配置", notes="获取积木打印配置-")
	 @GetMapping(value = "/getPrintConfig")
	 public Result<?> getPrintConfig(@RequestParam(name="dbCode",required=true) String dbCode) {

		 /**
		  * printConfigObj.put("rowsObj",rowsObj);
		  * printConfigObj.put("rowHeight",rowHeight); float[] rowHeight
		  * printConfigObj.put("colWidth",colWidth);	float[] colWidth
		  * printConfigObj.put("merges",mergesObj); 合并 row_col 1_2
		  * printConfigObj.put("areaWidth",areaWidth);
		  * printConfigObj.put("areaHeight",areaHeight);
		  * printConfigObj.put("printConfig",printConfig);
		  */
		 JSONObject printConfig = chgBillService.getPrintConfig(dbCode);
		 return Result.OK(printConfig);

	 }



	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收费明细-通过主表ID查询")
	@ApiOperation(value="收费明细-通过主表ID查询", notes="收费明细-通过主表ID查询")
	@GetMapping(value = "/queryChgSubFeesByMainId")
	public Result<?> queryChgSubFeesListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ChgSubFees> chgSubFeesList = chgSubFeesService.selectByMainId(id);
		IPage <ChgSubFees> page = new Page<>();
		page.setRecords(chgSubFeesList);
		page.setTotal(chgSubFeesList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param chgFees
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChgFees chgFees) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ChgFees> queryWrapper = QueryGenerator.initQueryWrapper(chgFees, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ChgFees> queryList = chgFeesService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ChgFees> chgFeesList = new ArrayList<ChgFees>();
      if(oConvertUtils.isEmpty(selections)) {
          chgFeesList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          chgFeesList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ChgFeesPage> pageList = new ArrayList<ChgFeesPage>();
      for (ChgFees main : chgFeesList) {
          ChgFeesPage vo = new ChgFeesPage();
          BeanUtils.copyProperties(main, vo);
          List<ChgSubFees> chgSubFeesList = chgSubFeesService.selectByMainId(main.getId());
          vo.setChgSubFeesList(chgSubFeesList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "收费记录列表");
      mv.addObject(NormalExcelConstants.CLASS, ChgFeesPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("收费记录数据", "导出人:"+sysUser.getRealname(), "收费记录"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ChgFeesPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ChgFeesPage.class, params);
              for (ChgFeesPage page : list) {
                  ChgFees po = new ChgFees();
                  BeanUtils.copyProperties(page, po);
                  chgFeesService.saveMain(po, page.getChgSubFeesList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
